package nl.ruudshuis.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

import nl.ruudshuis.beans.VeilingBean;
import nl.ruudshuis.db.DBmanager;

public class VeilingDao {

	private String sqlBiedingread = "SELECT * FROM VEILING";
	private String sqlBiedingcreate = "";
	private String sqlBiedingupdate = "";

	private Connection con = null;
	private PreparedStatement psRead = null;
	private PreparedStatement psCreate = null;
	private PreparedStatement psUpdate = null;

	public VeilingDao(DBmanager db) {
		DBmanager myDb = db;
		con = myDb.getConnection();
		try {

			this.psRead = con.prepareStatement(sqlBiedingread);
			this.psCreate = con.prepareStatement(sqlBiedingcreate);
			this.psUpdate = con.prepareStatement(sqlBiedingupdate);

		} catch (SQLException se) {
			printSQLException(se);
		}
	}

	public LinkedList<VeilingBean> getVeilingen() {

		LinkedList<VeilingBean> veilingen = new LinkedList<VeilingBean>();

		try {
			ResultSet rs = psRead.executeQuery();

			while (rs.next()) {
				
			}

			rs.close();

		} catch (SQLException se) {
			printSQLException(se);
		}

		return veilingen;
	}

	public void createVeiling(String f) {

		try {

			psCreate.clearParameters();

			psCreate.setDate(1, new java.sql.Date(System.currentTimeMillis()));
			psCreate.setInt(2, 1);
			psCreate.setString(3, f);
			psCreate.setDate(4, new java.sql.Date(System.currentTimeMillis()));

			int resultaat = psCreate.executeUpdate();
			if (resultaat == 0) {
				System.out.println("nix done");
			}
		} catch (SQLException se) {
			printSQLException(se);
		}
	}

	public void updateUrl(String f) {

		// Hmm, transacties?

		try {

			psUpdate.clearParameters();

			int verhoging = 0;
			Statement s = con.createStatement();
			ResultSet rs = s
					.executeQuery("select timesVisited from URL where fullname='"
							+ f + "'");

			if (rs.next()) {
				verhoging = rs.getInt(1);
			}
			rs.close();

			psUpdate.setInt(1, ++verhoging);
			psUpdate.setString(2, f);

			int resultaat = psUpdate.executeUpdate();
			if (resultaat == 0) {
				System.out.println("nix done");
			}
		} catch (SQLException se) {
			printSQLException(se);
		}
	}

	private void printSQLException(SQLException se) {
		while (se != null) {

			System.out.print("SQLException: State:   " + se.getSQLState());
			System.out.println("Severity: " + se.getErrorCode());
			System.out.println(se.getMessage());

			se = se.getNextException();
		}
	}

}
